package jrmob.yonyou.com.commonlib.app_config_tool.tool.base;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;

/**
 * 字符串操作工具包
 */
public class StringUtil {
    private static GregorianCalendar calendar = new GregorianCalendar();
    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
    private final static SimpleDateFormat dateFormater = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    private final static SimpleDateFormat dateFormater2 = new SimpleDateFormat(
            "yyyy-MM-dd");
    private final static SimpleDateFormat dateFormater3 = new SimpleDateFormat(
            "MM-dd HH:mm");
    private final static SimpleDateFormat dateFormater4 = new SimpleDateFormat(
            "HH:mm");

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 功能:  当天的开始时间
     * <p>
     * 日 期: 2016/8/3
     */
    public static Long getStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime().getTime();
    }


    /**
     * 功能:  当天的结束时间
     * <p>
     * 日 期: 2016/8/3
     */
    public static Long getEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime().getTime();
    }

    /**
     * 将url地址中"：//"等转换"%"
     *
     * @param url
     * @return
     */
    public static String urlToString(String url) {
        try {
            return URLEncoder.encode(url, "utf8");
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate) {
        Date time = toDate(sdate);
        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = dateFormater2.format(cal.getTime());
        String paramDate = dateFormater2.format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天 " + dateFormater4.format(time);
        } else if (days == 2) {
            ftime = "前天 " + dateFormater4.format(time);
        } else {
            ftime = dateFormater3.format(time);
        }
        return ftime;
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.format(today);
            String timeDate = dateFormater2.format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 获取当前时间字符串"yyyy-MM-d HH:mm:ss"
     *
     * @return
     */
    public static String getDateString() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-d HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 根据输入的毫秒数，获得日期
     *
     * @param millis
     * @return
     */
    public static int getDay(long millis) {
        calendar.setTimeInMillis(millis);
        return calendar.get(Calendar.DATE);
    }

    /**
     * 获得当前时间的毫秒表示
     *
     * @return
     */
    public static long getNow() {
        GregorianCalendar now = new GregorianCalendar();
        return now.getTimeInMillis();

    }

    /**
     * 根据输入的毫秒数，获得日期字符串
     *
     * @param millis
     * @return
     */
    public static String getDate(long millis) {
        calendar.setTimeInMillis(millis);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(calendar.getTime());
    }

    /**
     * 获取今天
     *
     * @return
     */
    public static String getToday() {
        return getDate(getNow());
    }

    /**
     * 获取后天日期
     *
     * @return
     */
    public static String getTheDayData() {
        return getDate(getNow() + 86400000 + 86400000);
    }

    /**
     * 获取明天日期
     *
     * @return
     */
    public static String getTomorrow() {
        return getDate(getNow() + 86400000);
    }

    /**
     * 获取昨天日期
     *
     * @return
     */
    public static String getYesterday() {
        return getDate(getNow() - 86400000);
    }

    /**
     * 获取x天前或后的日期
     *
     * @param x 正数表示之后 负数表示之前
     * @return
     */
    public static String getXDayBeforeOrAfter(int x) {
        long tempX = (long) x;
        if (tempX > 0) {
            return getDate(getNow() + (86400000 * tempX));
        } else {
            return getDate(getNow() - 86400000 * Math.abs(tempX));
        }
    }

    /**
     * 根据标准日获取x天前或后的日期
     *
     * @param x       正数表示之后 负数表示之前
     * @param baseDay 标准日
     * @return
     */
    public static String getXDayBeforeOrAfterWithBaseDay(Date baseDay, int x) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.format(baseDay);
        return getDate(sdf.getCalendar().getTimeInMillis() + 86400000 * x);
    }

    /**
     * 获取前天日期
     *
     * @return
     */
    public static String getTheBeforeYesterday() {
        return getDate(getNow() - 86400000 - 86400000);
    }

    /**
     * @desc 获取时间上下午
     */

    public static int getAMPM(String time) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date date = formatter.parse(time);
        calendar.setTime(date);
        return calendar.get(GregorianCalendar.AM_PM);
    }
    /**
     * 当前时间字符串做文件名
     *
     * @return
     */
    public static String getFileName() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 判断是否为合法IP
     *
     * @return the ip
     */
    public static boolean isboolIp(String ipAddress) {
        String ip = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    /**
     * 获取指定长度的随机字符串
     */
    public static String randomString(int len) {
        Random randGen = new Random();

        char[] letters = ("0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
                .toCharArray();

        if (len < 1) {
            return null;
        }

        char[] buf = new char[len];
        for (int i = 0; i < len; i++) {
            buf[i] = letters[randGen.nextInt(71)];
        }
        return new String(buf);
    }

    /**
     * GZIP解压
     *
     * @param paramArrayOfByte
     * @return
     * @throws IOException
     */
    public static String uncompress(byte[] paramArrayOfByte) throws IOException {
        ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
        GZIPInputStream localGZIPInputStream = new GZIPInputStream(
                new ByteArrayInputStream(paramArrayOfByte));
        byte[] arrayOfByte = new byte[256];
        int length = 0;

        while ((length = localGZIPInputStream.read(arrayOfByte)) != -1) {
            localByteArrayOutputStream.write(arrayOfByte, 0, length);
        }
        return localByteArrayOutputStream.toString();
    }

    /**
     * 获取lasttime
     *
     * @param context
     * @param key
     * @return
     */
    public static String getLasttime(Context context, String key) {
        String lasttime = StringUtil.getPrefereceFileKeyValue(context, key);
        if ("".equals(lasttime) || lasttime == null) {
            lasttime = "2008-12-05 12:45:08";
        }
        return lasttime;
    }

//    /**
//     * 本地存值
//     *
//     * @param context
//     * @param key
//     * @param value
//     */
//    public static void createPrefereceFile(Context context, String key,
//                                           String value) {
//        SharedPreferences prefs = PreferenceManager
//                .getDefaultSharedPreferences(context);
//        SharedPreferences.Editor edit = prefs.edit();
//        edit.putString(key, value);
//        edit.commit();
//    }

//    /**
//     * 清空本地值
//     *
//     * @param context
//     * @param key
//     */
//    public static void clearPrefereceFile(Context context, String key) {
//        SharedPreferences prefs = PreferenceManager
//                .getDefaultSharedPreferences(context);
//        SharedPreferences.Editor edit = prefs.edit();
//        edit.remove(key);
//        edit.commit();
//    }

    /**
     * 本地取值
     *
     * @param context
     * @param key
     * @return
     */
    public static String getPrefereceFileKeyValue(Context context, String key) {
//        SharedPreferences prefs = PreferenceManager
//                .getDefaultSharedPreferences(context);
        String value = BaseActivityMob_lib.readLocationValue(key);
        return value;
    }

    /**
     * 输入框过滤器 过滤表情符 TODO
     *
     * @return
     */
    public static InputFilter[] getInputFilter() {
        InputFilter[] emojiFilter = new InputFilter[]{new InputFilter() {
            Pattern emoji = Pattern
                    .compile(
                            "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                            Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            public CharSequence filter(CharSequence src, int start, int end,
                                       Spanned dst, int dstart, int dend) {
                Matcher emojiMatcher = emoji.matcher(src);
                if (emojiMatcher.find()) {
                    return "";
                }
                return null;
            }
        }, new InputFilter.LengthFilter(20)};
        return emojiFilter;
    }

    /**
     * 解析个人详细信息Hml标签
     * <p>
     * author chensong
     *
     * @param htmlStr
     * @return
     */
    public static HashMap<String, String> getHtmlContent(String htmlStr) {
        HashMap<String, String> mMap = new HashMap<String, String>();
        String[] classifyID = {"userTitle", "userPost", "companyTel",
                "Iphone", "homeNumber", "fax"};
        String regEx_html[] = {"<Title>([^</Title>]*)", "<Rank>([^</Rank>]*)",
                "<CompanyPhone>([^</CompanyPhone>]*)",
                "<mobile>([^</mobile>]*)", "<HomePhone>([^</HomePhone>]*)",
                "<faxnum>([^</faxnum>]*)"};// 定义HTML标签的正则表达式

        for (int i = 0; i < regEx_html.length; i++) {
            Pattern p = Pattern.compile(regEx_html[i]);// 匹配<title>开头，</title>结尾的文档
            Matcher m = p.matcher(htmlStr);// 开始编译
            // html = m.replaceAll(";"); // 过滤html标签
            while (m.find()) {
                System.out.println("getContext------------>" + m.group(1) + ";"
                        + classifyID[i]);
                mMap.put(classifyID[i], m.group(1));// 获取被匹配的部分
            }
        }
        return mMap;
    }

    /**
     * 去掉数字字符串末尾的0
     *
     * @param s
     * @return
     */
    public static String deleteZero(String s) {
        int i = s.length() - 1;
        for (; i >= 0; ) {
            if (s.charAt(i) == '0') {
                i--;
            } else {
                break;
            }
        }
        if (s.charAt(i) == '.') {
            return s.substring(0, i);
        }
        return s.substring(0, i + 1);
    }


    public static List<Date> dateSplit(Date start, Date end)
            throws Exception {
        if (!start.before(end))
            throw new Exception("开始时间应该在结束时间之后");
        Long spi = end.getTime() - start.getTime();
        Long step = spi / (24 * 60 * 60 * 1000);// 相隔天数

        List<Date> dateList = new ArrayList<Date>();
        dateList.add(end);
        for (int i = 1; i <= step; i++) {
            dateList.add(new Date(dateList.get(i - 1).getTime()
                    - (24 * 60 * 60 * 1000)));// 比上一天减一
        }
        return dateList;
    }
}